package com.inspur.edp.ai.flow.core.engine;

import com.inspur.edp.ai.flow.api.FlowMetadataService;
import com.inspur.edp.ai.flow.api.ServiceContainer;
import com.inspur.edp.ai.flow.metadata.FlowMetadata;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lizhaorui
 * @date 2025/8/19
 * @description
 */
public class FlowRTCacheManager {

    private volatile static FlowRTCacheManager instance;

    private ConcurrentHashMap<String, FlowRTObject> rtObjectMap;

    private FlowMetadataService metadataService;

    public static FlowRTCacheManager getInstance() {
        if (instance == null) {
            synchronized (FlowRTCacheManager.class) {
                if (instance == null) {
                    FlowRTCacheManager cacheMgr = new FlowRTCacheManager();
                    cacheMgr.rtObjectMap = new ConcurrentHashMap<>();
                    cacheMgr.metadataService = ServiceContainer.getService(FlowMetadataService.class);
                    instance = cacheMgr;
                }
            }
        }
        return instance;
    }

    public FlowRTObject getRTObject(String flowId) {
        if (rtObjectMap.containsKey(flowId)) {
            return rtObjectMap.get(flowId);
        } else {
            synchronized (FlowRTCacheManager.class) {
                if (rtObjectMap.containsKey(flowId)) {
                    return rtObjectMap.get(flowId);
                } else {
                    FlowRTObjectLoader flowRTObjectLoader = new FlowRTObjectLoader();
                    FlowMetadata metadata = this.metadataService.retrieve(flowId);
                    FlowRTObject ruleRTObject = flowRTObjectLoader.load(metadata);
                    rtObjectMap.put(flowId, ruleRTObject);
                    return ruleRTObject;
                }
            }
        }
    }

    public void clear(String bizTypeId) {
        synchronized (FlowRTCacheManager.class) {
            this.rtObjectMap.remove(bizTypeId);
        }
    }


}